//
//  HKListAdapter.m
//  KSBridgeDesign
//
//  Created by huzhaoke on 2021/4/17.
//

#import "HKListAdapter.h"
#import "UIScrollView+otherDelegate.h"

const CGFloat kKSAdatperLoadMoreDefaultOffset = 100;

@interface HKListAdapter () <UIScrollViewDelegate>

@property (nonatomic, assign, readwrite) NSUInteger sectionCount;
@property (nonatomic, assign, readwrite) BOOL isEmpty;

@property (nonatomic, weak) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableSet<NSString *> *cellIdentifiers;
@property (nonatomic, strong) NSMutableSet<NSString *> *headerFooterIdentifiers;

@end

@implementation HKListAdapter

- (instancetype)initWithView:(__kindof UIScrollView *)view {
    NSAssert([view isKindOfClass:UITableView.class] || [view isKindOfClass:UICollectionView.class], @"view 只能是UITableView/UICollectionView");
    if (![view isKindOfClass:UITableView.class] && ![view isKindOfClass:UICollectionView.class]) {
        return nil;
    }
    self = [super init];
    if (self) {
        _sectionModels = [NSMutableArray array];
        view.delegate = self;
        _scrollView = view;
        _cellIdentifiers = [NSMutableSet set];
        _headerFooterIdentifiers = [NSMutableSet set];
    }
    return self;
}

- (NSUInteger)sectionCount {
    return self.sectionModels.count;
}

- (BOOL)isEmpty {
    return self.sectionModels.count == 0;
}

- (HKListSectionModel *)sectionModelInSection:(NSUInteger)section {
    if (section >= _sectionModels.count) {
        return nil;
    }
    return _sectionModels[section];
}

- (NSUInteger)indexOfSectionModel:(HKListSectionModel *)sectionModel {
    if (!sectionModel) {
        return NSNotFound;
    }
    return [_sectionModels indexOfObject:sectionModel];
}

- (NSUInteger)cellCountInSection:(NSUInteger)section {
    return [self sectionModelAtSection:section].cellModels.count;
}


- (NSIndexPath *)indexPathOfCellModel:(HKListCellModel *)cellModel {
    if (!cellModel) {
        return nil;
    }
    
    if (cellModel.sectionModel) {
        NSUInteger section = [self indexOfSectionModel:cellModel.sectionModel];
        NSUInteger row = [cellModel.sectionModel indexOfCellModel:cellModel];
        
        return (section != NSNotFound && row != NSNotFound) ? [NSIndexPath indexPathForRow:row inSection:section] : nil;
    } else {
        __block NSIndexPath *indexPath = nil;
        [_sectionModels enumerateObjectsUsingBlock:^(HKListSectionModel * _Nonnull sectionModel, NSUInteger section, BOOL * _Nonnull stop) {
            NSUInteger row = [sectionModel indexOfCellModel:cellModel];
            if (row != NSNotFound) {
                indexPath = [NSIndexPath indexPathForRow:row inSection:section];
                *stop = YES;
            }
        }];
        return indexPath;
    }
}

- (NSUInteger)cellModelsCountAtSection:(NSUInteger)section {
    HKListSectionModel *sectionModel = [self sectionModelAtSection:section];
    return [sectionModel cellModelCount];
}

- (nullable HKListSectionModel *)sectionModelAtSection:(NSUInteger)section {
    if (section >= self.sectionModels.count) {
        return nil;
    }
    return self.sectionModels[section];
}

- (nullable HKListCellModel *)cellModelAtIndexPath:(NSIndexPath *)indexPath {
    HKListSectionModel *sectionModel = [self sectionModelAtSection:indexPath.section];
    return [sectionModel cellModelAtIndex:indexPath.row];
}

//Handle SectionModels, 添加和删除都是safe方法，复杂操作，使用sectionModels
- (void)clear {
    [self.sectionModels removeAllObjects];
}

- (void)addSectionModel:(HKListSectionModel *)sectionModel {
    if (!sectionModel) {
        return;
    }
    [self.sectionModels addObject:sectionModel];
}

- (void)addSectionModels:(NSArray<HKListSectionModel *> *)sectionModels {
    if (sectionModels.count == 0) {
        return;
    }
    [self.sectionModels addObjectsFromArray:sectionModels];
}

- (void)insertSectionModel:(HKListSectionModel *)sectionModel atIndex:(NSUInteger)index {
    if (index > self.sectionCount || !sectionModel) {
        return;
    }
    [self.sectionModels insertObject:sectionModel atIndex:index];
}

- (void)insertSectionModels:(NSArray<HKListSectionModel *> *)sectionModels atIndex:(NSUInteger)index {
    if (index > self.sectionCount || sectionModels.count == 0) {
        return;
    }
    [self.sectionModels insertObjects:sectionModels atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index, sectionModels.count)]];
    
}

- (void)removeSectionModel:(HKListSectionModel *)sectionModel {
    if (!sectionModel) {
        return;
    }
    [self.sectionModels removeObject:sectionModel];
}

- (void)removeSectionModels:(NSArray<HKListSectionModel *> *)sectionModels {
    if (sectionModels.count == 0) {
        return;
    }
    [self.sectionModels removeObjectsInArray:sectionModels];
}
- (void)removeSectionModelAtIndex:(NSUInteger)index {
    if (index >= self.sectionCount) {
        return;
    }
    [self.sectionModels removeObjectAtIndex:index];
}

- (NSArray<HKListSectionModel *> *)subSectionModelsFromIndex:(NSUInteger)fromIndex {
    return [self subSectionModelsFromIndex:fromIndex toIndex:self.sectionCount];
}

- (NSArray<HKListSectionModel *> *)subSectionModelsToIndex:(NSUInteger)toIndex {
    return [self subSectionModelsFromIndex:0 toIndex:toIndex];
}

- (NSArray<HKListSectionModel *> *)subSectionModelsFromIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex {
    NSUInteger sectionCount = self.sectionCount;
    if (toIndex > sectionCount) {
        toIndex = sectionCount;
    }
    if (toIndex <= fromIndex) {
        return @[];
    }
    return [self.sectionModels subarrayWithRange:NSMakeRange(fromIndex, toIndex - fromIndex)];
}

- (nullable HKListCellModel *)cellModelForCell:(__kindof UIView *)cell {
    return nil;
}

- (void)performBatchUpdates:(void (NS_NOESCAPE ^)(__kindof HKListAdapter *adapter))updates
                   animated:(BOOL)animated
                 completion:(void (^ _Nullable)(BOOL finished))completion {
    
}

#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self triggerLoadMoreIfNeeded];
    if ([self.scrollViewDelegate respondsToSelector:@selector(scrollViewDidScroll:)]) {
        [self.scrollViewDelegate scrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self triggerLoadMoreIfNeeded];
}

#pragma mark - loadMore
- (void)triggerLoadMoreIfNeeded {
    //  如果没有设置block，则认为没有必要进行下面的判断
    if (!self.loadMoreDelegate || self.isLoading) {
        return;
    }
    if ([self.loadMoreDelegate respondsToSelector:@selector(triggerLoadMoreIfNeeded:)]) {
        [self.loadMoreDelegate triggerLoadMoreIfNeeded:self];
        return;
    }
    CGFloat offset = [self.loadMoreDelegate adapterLoadMoreOffset:self];
    CGFloat contentOffsetY = self.scrollView.contentOffset.y;
    CGFloat contentSizeHeight = self.scrollView.contentSize.height;
    CGFloat tableHeight = self.scrollView.frame.size.height;
    if (contentOffsetY > 0 && contentOffsetY > contentSizeHeight - tableHeight - offset) {
        self.isLoading = YES;
        [self.loadMoreDelegate adapterOnLoadMore:self];
    }
}

@end

@implementation HKListAdapter (Private)

- (void)addCellIdentifier:(NSString *)identifier {
    if (identifier.length == 0) {
        return;
    }
    [self.cellIdentifiers addObject:identifier];
}

- (void)addHeaderFooterIdentifier:(NSString *)identifier {
    if (identifier.length == 0) {
        return;
    }
    [self.headerFooterIdentifiers addObject:identifier];
}

- (BOOL)containsCellIdentifier:(NSString *)identifier {
    return [self.cellIdentifiers containsObject:identifier];
}

- (BOOL)containsHeaderFooterIdentifier:(NSString *)identifier {
    return [self.headerFooterIdentifiers containsObject:identifier];
}

@end
